<script>
import PreviewImage from '@/components/PreviewImage.vue'

export default {
  name: 'UploadImage',
  components: { PreviewImage },
  data () {
    return {
      headers: {
        token: this.$cookies.get('token')
      }
    }
  },
  props: {
    limit: {
      type: Number,
      default: 1
    },
    imageList: {
      type: Array,
      required: true,
      default: function () {
        return []
      }
    },
    size: {
      type: Number,
      default: 10
    },
    imageKey: String,
    data: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  methods: {
    onExceed () {
      this.$message.error(`最多上传${this.limit}条数据!`)
    },
    async beforeRemove () {
      await this.$confirm('确定删除该图片吗?', { type: 'info', title: '询问' }).then(() => {
        return true
      })
    },
    onRemove (file) {
      let index = -1
      for (let i = 0; i < this.imageList.length; i++) {
        if (this.imageList[i].name === file.name) {
          index = i
          break
        }
      }
      if (index > -1) {
        this.$emit('delete', { imageKey: this.imageKey, index })
      }
    },
    beforeUpload (file) {
      const isImage = file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/gif'
      if (!isImage) {
        this.$message.error('请上传正确格式的图片！')
      }
      const size = file.size / 1024 / 1024 < this.size
      if (!size) {
        this.$message.error(`图片不能超过${this.size}M！`)
      }
      return isImage && size
    },
    onPreview (file) {
      this.$refs.previewImage.setImageList(file.name)
    },
    onSuccess (res) {
      if (res.code === 200) {
        this.$emit('success', { imageKey: this.imageKey, filename: res.data.fileName })
      } else {
        this.$message.error(res.msg)
      }
    }
  }
}
</script>

<template>
  <div>
    <el-upload
      action="/api/upload"
      list-type="picture-card"
      :headers="headers"
      :limit="limit"
      :file-list="imageList"
      :on-exceed="onExceed"
      :before-remove="beforeRemove"
      :before-upload="beforeUpload"
      :on-success="onSuccess"
      :on-preview="onPreview"
      :on-remove="onRemove"
      accept=".jpg,.png,.gif,.jpeg"
      :data="data">
      <i class="el-icon-plus"></i>
    </el-upload>
    <preview-image ref="previewImage"/>
  </div>
</template>

<style scoped lang="scss">

</style>
